home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1739 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  56 lines

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: swap high and low 16 bits?
  5. Date: Tue, 16 Jan 96 17:06:29 GMT
  6. Organization: none
  7. Message-ID: <821811989snz@genesis.demon.co.uk>
  8. References: <Pine.OSF.3.91.960115174921.19742A-100000@io.UWinnipeg.ca>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <Pine.OSF.3.91.960115174921.19742A-100000@io.UWinnipeg.ca>
  15.            wsimpson@uwinnipeg.ca "Bill Simpson" writes:
  16.  
  17. >I wanted to obtain a "random" starting number each time a program
  18. >is run.  The obvious choice is time(NULL).  The problem with it is that
  19. >if the program runs and terminates fairly quickly, the number returned by 
  20. >time(NULL) is quite similar each run, differing only by the lowest bits.
  21. >
  22. >One solution would be to swap the high 16 bits and the low 16 bits of the
  23. >32 bit unsigned long int.  Sorry this is dirty, not ANSI.
  24.  
  25. OK, I assume then you have something like :
  26.  
  27. #include <time.h>
  28.  
  29.     unsigned long val;
  30.  
  31.     val = time(NULL);
  32.  
  33. That's not strictly portable (for instance time_t could have type double
  34. and the conversion to unsigned long could trap) but works on many
  35. implementations.
  36.  
  37. One simple approach would be to call your random funciton (rand() or whatever)
  38. a few times and discard the values. The 2 random number sequences should
  39. diverge quickly for a reasonable RNG algorithm. Another approach might be
  40.  
  41.     ...
  42.     val *= N;
  43.  
  44. where N is a large odd number. Unsigned arithmetic is modulo arithmetic - it
  45. can't overflow. Alternatively you could do something like:
  46.  
  47.     val ^= val << 16;
  48.  
  49. which will cause variation in higher order bits for small changes of val.
  50.  
  51. -- 
  52. -----------------------------------------
  53. Lawrence Kirby | fred@genesis.demon.co.uk
  54. Wilts, England | 70734.126@compuserve.com
  55. -----------------------------------------
  56.